package cn.chaos.bio01;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPOutputStream;

public class CompressProtocol implements Runnable {
    
    public static final int BUFSIZE = 1024;
    private Socket clientSocket;
    
    private Logger logger;
    
    public CompressProtocol(Socket clientSocket, Logger logger) {
        this.clientSocket = clientSocket;
        this.logger = logger;
    }
    
    
    public static void handleCompressClient(Socket clientSocket, Logger logger) {
        try {
            InputStream in = clientSocket.getInputStream();
            GZIPOutputStream out = new GZIPOutputStream(clientSocket.getOutputStream());
            
            byte[] buffer = new byte[BUFSIZE];
            
            int bytesRead;
            
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.finish();
            
            logger.info("Client "+ clientSocket.getRemoteSocketAddress() +" finished");
        } catch (IOException e) {
            logger.log(Level.WARNING, "Exception in echo protocol", e);
        }
        
        try {
            clientSocket.close();
        } catch (IOException e) {
            logger.info("Exception = "+ e.getMessage());
        }
    }
    
    @Override
    public void run() {
        
        handleCompressClient(this.clientSocket, this.logger);
    }

}
